package cn.yto.print.plugins;

import cn.yto.print.config.i18n.I18nResourceManager;
import cn.yto.print.constants.AssistantConstants;
import cn.yto.print.controller.IndexController;
import cn.yto.print.enums.MessageTypeEnum;
import cn.yto.print.enums.PluginRegistryEnum;
import cn.yto.print.listener.PluginInstalledMonitor;
import cn.yto.print.listener.SoftwareListener;
import cn.yto.print.system.SpringContextHolder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class PluginSupplyRunnable implements Runnable {

    private static final Logger logger = LogManager.getLogger(PluginSupplyRunnable.class);

    @Override
    public void run() {
        for (PluginRegistryEnum currentPlugin : PluginRegistryEnum.values()) {
            PluginInstalledMonitor monitorInstance = PluginInstalledMonitor.getInstance();
            SoftwareListener listener = new SoftwareListener() {
                @Override
                public void installedComplete(PluginRegistryEnum plugin) {
                    logger.info("【{}】打印组件已经安装，进程监控中 ...", plugin.getName());
                    IndexController.setPluginInstalledShow(plugin, AssistantConstants.INSTALLED);
                    String msg = String.format(
                            I18nResourceManager.getInstance().get("index.console.listener"),
                            I18nResourceManager.getInstance().get(plugin.getLocale())
                    );
                    SpringContextHolder.getBean(IndexController.class).addConsoleLog(msg, MessageTypeEnum.INFO);
                }

                @Override
                public void uninstallComplete(PluginRegistryEnum plugin) {
                    logger.info("【{}】打印组件没有安装", plugin.getName());
                    IndexController.setPluginInstalledShow(plugin, AssistantConstants.UNINSTALL);
                    String msg = String.format(
                            I18nResourceManager.getInstance().get("index.console.uninstall"),
                            I18nResourceManager.getInstance().get(plugin.getLocale())
                    );
                    SpringContextHolder.getBean(IndexController.class).addConsoleLog(msg, MessageTypeEnum.INFO);
                }
            };
            monitorInstance.addInstalledListener(currentPlugin, listener);
        }
    }

}

